const app = getApp();
const _requsetCYZ = require('../../../utils/requestData');
const _functionCYZ = require('../../../utils/common');
var WxParse = require('../../../wxParse/wxParse.js');
const QQMapWX = require('../../../utils/qqmap-wx-jssdk.min.js'); // 引入SDK核心类
let goodsSpecArr = [];
Page({
    data: {
        isLoadingData:true,
		this_shop_config_c: null,
		this_config_op:{},
        this_user_info: {},
        swiperAutoPlay:true,
        swiperInterval:5000,
        this_g_nav: 1,
        this_goods_id: 0,
        this_shop_id: 0,
        this_goods_info: null,
        goods_specification: [],
        goods_add_card_show: false,
        cart_default_number: 1,
        goods_attr_select: {},
        shop_price:'0.00',
        market_price:'0.00',
        stock_num:0,
        sku_id: 0,
        skuCoverImage:'',
        this_spec_type: 1,
        this_spec_attr: [],
        this_spec_list: [],
        choose_spec_list: [],
        btn_add_cart_disabled: false,
        scrollTop: 0,
        floorstatus: true,
        is_add_cart_view: false,
        is_buy_now_view: false,
        this_login_user_id: 0,
        shop_attr_price: [],
        show_share: false,
        this_isshare_timeline: false,
        video_is_play:false,
        back_top:0,
        back_height:0
    },
    changeCartNumber: function (e) {
        this.setData({
            cart_default_number: e.detail.value
        });
    },
    show_share_bind: function () {
        this.setData({
            show_share: this.data.show_share ? false : true
        });
    },
    go_business_info: function () {
        wx.redirectTo({
            url: '/pages/business_detail/index?id=' + this.data.this_shop_id
        });
    },
    /**
     * 跳转页面
     */
    onAppNavigateTap: function (e) {
        const dataset = e.detail.target ? e.detail.target.dataset : e.currentTarget.dataset;
        const url = dataset.url,
            appurl = dataset.appurl,
            atype = dataset.atype || 1,
            appId = dataset.appid;
        if (atype == 1) {
            wx.navigateTo({
                url: url,
                fail: () => {
                    wx.switchTab({
                        url: url,
                    });
                }
            });
        } else if (atype == 2) {
            wx.navigateToMiniProgram({
                appId: appId,
                path: appurl
            });
        }
    },
    goTop: function (e) {
        this.setData({
            scrollTop: 0
        })
    },
    onLoad: function (op) {
		var that = this;
		console.log(wx.getLaunchOptionsSync())

        let share_openid = op.share_openid || '';
        if (share_openid) {
            wx.setStorageSync('global_share_r_openid', share_openid);
        }
        let lau_option = wx.getLaunchOptionsSync();
        if (lau_option.scene == 1154) { //分享朋友圈
            that.setData({
                this_isshare_timeline: true
            });
        } else {
            that.setData({
                this_isshare_timeline: false
            });
        }

        let goods_id = 0;
        let tg_user_id = 0;
        if (op.goods_id != undefined) {
            goods_id = op.goods_id;
        } else if (op.scene != undefined) {
            let scene = decodeURIComponent(op.scene);
            let scene_data = scene.split("#");
            goods_id = scene_data[1] || 0;
            tg_user_id = scene_data[0] || 0;
        }
        that.setData({
			this_goods_id: goods_id,
			this_config_op: op
		});

		let clientRect = wx.getMenuButtonBoundingClientRect();
        that.setData({
          back_height:(clientRect.bottom - clientRect.top),
          back_top:clientRect.top
        })

		if (!that.data.this_isshare_timeline) {
            that.getLocation();
        } else {
            that.get_index_data();
        }
    },
    onShow: function () {
        if (wx.getStorageSync('is_auth_login_back') == 1) {
            wx.setStorageSync('is_auth_login_back', null);
            this.get_index_data();
        }
    },
    navigateBack_btn:function(){
      wx.navigateBack({
        delta: 0,
        fail:function(){
          wx.switchTab({
            url: '../shop_index/index'
          })
        }
      })
	},
	//获取用户位置信息
    getLocation: function () {
        const that = this;
        let qqmakSdk = null;
        _requsetCYZ.cyz_requestGet('/ShopApi/getShopQQMapKeyV2', {}, function (res) {
            if(res.info.is_get_location == 1){
                _functionCYZ.CYZ_loading("定位中，请稍候...");
                wx.getLocation({
                    type: 'wgs84',
                    success: function (res) {
                        wx.setStorageSync('global_u_lat', res.latitude || 0);
                        wx.setStorageSync('global_u_lng', res.longitude || 0);
                        wx.setStorageSync('global_u_address', '');
                        that.addFenxiaoAction();
                    },
                    fail: function () {
                        that.addFenxiaoAction();
                    }
                })
            }else{
                that.addFenxiaoAction();
            }
        });
	},
	addFenxiaoAction: function () {
        let that = this;
        let op = that.data.this_config_op;
        let goods_id = 0;
        let tg_user_id = 0;
        if (op.goods_id != undefined) {
            goods_id = op.goods_id;
        } else if (op.scene != undefined) {
            let scene = decodeURIComponent(op.scene);
            let scene_data = scene.split("#");
            goods_id = scene_data[1] || 0;
            tg_user_id = scene_data[0] || 0;
        }
        /*************添加推广************/
        if (!that.data.this_isshare_timeline) {
            if (op.scene != undefined) {
                let scene = decodeURIComponent(op.scene);
                let scene_data = scene.split("#");
                tg_user_id = scene_data[0] || 0;
            } else if (op.tg_user_id != undefined) {
                if (op.tg_user_id > 0) {
                    tg_user_id = op.tg_user_id || 0;
                }
            }
            var requestData = {};
            requestData.top_user_id = tg_user_id || 0;
            _requsetCYZ.cyz_requestGet('/ShopApi/addFenxiaoUser', requestData, function (cyz_data) {
                if (cyz_data.code == 1) {
                    that.get_index_data();
                } else if (cyz_data.code == 2) {
                    app.getUserDataToken(function (token) {
                        that.addFenxiaoAction();
                    });
                }
            });
        } else {
            that.get_index_data();
        }
        /*************添加推广************/
    },
    get_index_data: function () {
        var that = this;
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.goods_id = that.data.this_goods_id;
        if (that.data.this_isshare_timeline == true) {
            requestData.no_check_login = 1;
        } else {
            requestData.no_check_login = 0;
        }
        _requsetCYZ.cyz_requestGet('/ShopApi/getGoodsInfoV2', requestData, function (cyz_data) {
            wx.hideToast();
            if (cyz_data.code == 1) {
                that.setData({
                    this_goods_info: cyz_data.info,
                    sku_id: cyz_data.info.sku.sku_id,
                    shop_price:cyz_data.info.min_sales_price,
                    market_price:cyz_data.info.min_original_price,
                    stock_num:cyz_data.info.all_goods_num,
                    skuCoverImage:cyz_data.info.g_img,
                    this_spec_type: cyz_data.info.spec_type,
                    this_spec_attr: cyz_data.info.spec_attr,
                    this_spec_list: cyz_data.info.spec_list,
                    this_shop_id: cyz_data.info.shop_id,
                    this_login_user_id: cyz_data.info.login_user_id,
                    goods_specification: cyz_data.info.goods_specification,
                    this_shop_config_c: cyz_data.info.shop_info_c,
                    this_user_info: cyz_data.info.this_user_info,
                    isLoadingData:false
                });
                if(cyz_data.info.g_video_url != ''){
                    that.setData({swiperAutoPlay:false});
                }
                if(cyz_data.info.spec_type == 2){
                    let this_spec_attr = that.data.this_spec_attr;
                    goodsSpecArr = [];
                    for (let i in this_spec_attr) {
                        for (let j in this_spec_attr[i].spec_items) {
                            if (j < 1) {
                                this_spec_attr[i].spec_items[0].checked = true;
                                goodsSpecArr[i] = this_spec_attr[i].spec_items[0].item_id;
                            }
                        }
                    }
                    that.setData({this_spec_attr:this_spec_attr});
                    that._updateSpecGoods();
                }

                if (cyz_data.info != null) {
                    wx.setNavigationBarTitle({
                        title: cyz_data.info.g_name
                    });
                    WxParse.wxParse('article', 'html', cyz_data.info.g_description, that, 5);
                }
            } else if (cyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.get_index_data();
                });
                return false;
            }
        });
    },
    goods_nav_bind: function (e) {
        this.setData({
            this_g_nav: e.currentTarget.id
        });
    },
    //返回商城首页
    go_shop_index_bind: function () {
        wx.switchTab({
            url: '../shop_index/index'
        })
    },
    make_haibao_bind: function () {
        wx.navigateTo({
            url: '../ghaibao/index?id=' + this.data.this_goods_id,
        })
    },
    //图片放大
    img_max_bind: function (e) {
        var that = this;
        var img_max_url = e.currentTarget.dataset.url;
        var this_img_key = e.currentTarget.dataset.key;
        var all_img_num = that.data.this_goods_info.cmlist[this_img_key].com_imglist.length;
        var durls = [];
        for (var i = 0; i < all_img_num; i++) {
            durls[i] = that.data.this_goods_info.cmlist[this_img_key].com_imglist[i].imgurl;
        }
        wx.previewImage({
            current: img_max_url,
            urls: durls
        })
    },
    //链接跳转
    go_url_bind: function (e) {
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    //商品列表跳转
    go_goods_list_bind: function (e) {
        wx.navigateTo();
    },
    //商品详情跳转
    go_goods_info_bind: function (e) {
        console.log(e)
        wx.navigateTo({
            url: '../detail/index?goods_id=' + e.currentTarget.id
        });
    },
    //显示添加购物车
    goods_add_cart_bind: function () {
        this.setData({
            goods_add_card_show: true,
            is_add_cart_view: true,
            is_buy_now_view: false
        });
    },
    //隐藏添加购物车
    close_goods_add_cart: function () {
        this.setData({
            goods_add_card_show: false,
            is_add_cart_view: false,
            is_buy_now_view: false
        });
    },
    //进入购物车
    go_cart_list_bind: function (e) {
        wx.switchTab({
            url: '../cart/index'
        });
    },
    //减少数量
    bind_cart_number_jian: function () {
        var that = this;
        var this_default_number = parseInt(that.data.cart_default_number);
        if (this_default_number > 1) {
            that.setData({
                cart_default_number: this_default_number - 1
            });
        } else {
            that.setData({
                cart_default_number: 1
            });
        }
    },
    //增加数量
    bind_cart_number_jia: function () {
        var that = this;
        var this_default_number = parseInt(that.data.cart_default_number);
        that.setData({
            cart_default_number: this_default_number + 1
        });
    },
    //加入购物车
    goods_add_cart: function () {
        var that = this;
        //验证登陆
        if (that.data.this_user_info.user_auth_status != 2) {
            wx.navigateTo({
                url: '/pages/user/authorize/index',
            });
            return false;
        }
        that.setData({
            btn_add_cart_disabled: true
        });
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.shop_id = that.data.this_shop_id;
        requestData.gid = that.data.this_goods_id;
        requestData.gnumber = that.data.cart_default_number;
        requestData.goods_sku_id = that.data.sku_id;
        requestData.gattr = '';
        _requsetCYZ.cyz_requestPost('/ShopCartApi/addGoodsCartV2', requestData, function (cyz_data) {
            wx.hideToast();
            that.setData({
                btn_add_cart_disabled: false
            });
            if (cyz_data.code == 1) {
                wx.showToast({
                    title: '添加成功',
                    icon: 'success',
                    duration: 2000
                });
                that.close_goods_add_cart();
            } else if (cyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.goods_add_cart();
                });
                return false;
            } else {
                _functionCYZ.CYZ_alert(cyz_data.info);
                return false;
            }
        });
    },
    //
    //显示立即购买
    bind_goods_buy_now: function () {
        var that = this
        this.setData({
            goods_add_card_show: true,
            is_buy_now_view: true,
            is_add_cart_view: false
        });
    },
    //立即购买
    goods_buy_now: function () {
        var that = this;
        //验证登陆
        if (that.data.this_user_info.user_auth_status != 2) {
            wx.navigateTo({
                url: '/pages/user/authorize/index',
            });
            return false;
        }
        //验证是否绑定关系
        if (that.data.this_user_info.is_bind_referrer_user_id == 0) {
            wx.navigateTo({
                url: '/pages/user/authorize/bind_referrer',
            });
            return false;
        }
        that.setData({
            btn_add_cart_disabled: true
        });
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.shop_id = that.data.this_shop_id;
        requestData.gid = that.data.this_goods_id;
        requestData.gnumber = that.data.cart_default_number;
        requestData.goods_sku_id = that.data.sku_id;
        requestData.gattr = '';
        requestData.is_buy = 1;
        _requsetCYZ.cyz_requestPost('/ShopCartApi/addGoodsCartV2', requestData, function (cyz_data) {
            wx.hideToast();
            that.setData({
                btn_add_cart_disabled: false
            });
            if (cyz_data.code == 1) {
                wx.navigateTo({
                    url: '../submit/index?shop_id=' + that.data.this_shop_id
                })
            } else if (cyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.goods_buy_now();
                });
                return false;
            } else {
                _functionCYZ.CYZ_alert(cyz_data.info);
                return false;
            }
        });
    },
    //属性选择
    select_attr_bind: function (e) {
        var that = this
        var this_attr_id = e.currentTarget.id;
        var this_attr_name = e.currentTarget.dataset.type;
        var datas = that.data.goods_specification;
        var this_spec_price = 0;
        var a_datas = that.data.goods_attr_select;
        var g_datas = that.data.this_goods_info;
        var shop_attr_price = that.data.shop_attr_price;
        var this_shop_price = 0;
        var all_shop_price = 0;
        for (var i = 0; i < datas.length; i++) {
            if (datas[i].name == this_attr_name) {
                a_datas[datas[i].name] = null
                for (var j = 0; j < datas[i].values.length; j++) {
                    datas[i].values[j].ischeck = false
                    if (datas[i].values[j].id == this_attr_id) {
                        datas[i].values[j].ischeck = true
                        a_datas[datas[i].name] = this_attr_id
                        if (datas[i].values[j].format_price > 0) {
                            this_shop_price = datas[i].values[j].format_price
                        }
                    }
                }
                shop_attr_price[i] = this_shop_price
                that.setData({
                    shop_attr_price: shop_attr_price
                })
            }
            if (that.data.shop_attr_price[i]) {
                all_shop_price = that.data.shop_attr_price[i] * 1 + all_shop_price * 1
                all_shop_price = all_shop_price.toFixed(2);
            }
        }

        if (all_shop_price > 0) {
            g_datas.shop_price = all_shop_price
        }
        that.setData({
            goods_specification: datas,
            goods_attr_select: a_datas,
            this_goods_info: g_datas
        })
    },
    //收藏
    goods_shoucang_bind: function () {
        var that = this;
        _functionCYZ.CYZ_loading_n("操作中");
        var requestData = {};
        requestData.goods_id = that.data.this_goods_id;
        requestData.action_type = 'shoucang';
        _requsetCYZ.cyz_requestGet('/ShopApi/goodsShoucang', requestData, function (xyz_data) {
            wx.hideLoading();
            if (xyz_data.code == 1) {
                that.get_index_data();
                return true;
            } else if (xyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.goods_shoucang_bind();
                });
                return false;
            } else {
                _functionCYZ.CYZ_alert(xyz_data.info);
                return false;
            }
        });
    },
    onPullDownRefresh: function () {
        var that = this;
        that.get_index_data();
        setTimeout(() => {
            wx.stopPullDownRefresh()
        }, 1000);
    },
    onShareAppMessage: function () {
        var that = this;
        var shareTitle = that.data.this_goods_info.g_name;
        var sharePath = 'pages/shop/detail/index?goods_id=' + that.data.this_goods_id + '&tg_user_id=' + that.data.this_login_user_id;
        return {
            title: shareTitle,
            desc: '',
            path: sharePath
        }
    },
    onShareTimeline: function () {
        var that = this;
        return {
            title: that.data.this_goods_info.g_name,
            query: 'goods_id=' + that.data.this_goods_id + '&tg_user_id=' + that.data.this_login_user_id,
            imageUrl: that.data.this_goods_info.g_img
        }
    },
    //拨打电话
    call_phone_bind: function () {
        let k_phone = this.data.this_goods_info.shop_kefu_phone;
        if (!k_phone) return;
        wx.showModal({
            title: '温馨提示',
            content: '你将要拨打电话：' + k_phone,
            success: (res) => {
                if (res.cancel) return;
                wx.makePhoneCall({
                    phoneNumber: k_phone
                });
            }
        })
    },

    /**
     * 点击切换不同规格
     */
    onSwitchSpec: function (e) {
        let _this = this,
            attrIdx = e.currentTarget.dataset.attrIdx,
            itemIdx = e.currentTarget.dataset.itemIdx,
            spec_attr = _this.data.this_spec_attr;
        for (let i in spec_attr) {
            for (let j in spec_attr[i].spec_items) {
                if (attrIdx == i) {
                    spec_attr[i].spec_items[j].checked = false;
                    if (itemIdx == j) {
                        spec_attr[i].spec_items[itemIdx].checked = true;
                        goodsSpecArr[i] = spec_attr[i].spec_items[itemIdx].item_id;
                    }
                }
            }
        }
        _this.setData({
            this_spec_attr: spec_attr
        });
        // 更新商品规格信息
        _this._updateSpecGoods();
    },

    /**
     * 更新商品规格信息
     */
    _updateSpecGoods: function () {
        let _this = this,
            specSkuId = goodsSpecArr.join('_');
        // 查找skuItem
        let spec_list = _this.data.this_spec_list,
            skuItem = spec_list.find((val) => {
                return val.spec_sku_id == specSkuId;
            });
        // 记录goods_sku_id
        // 更新商品价格、划线价、库存
        if (typeof skuItem === 'object') {
            _this.setData({
                sku_id: skuItem.spec_sku_id,
                shop_price: skuItem.form.sales_price,
                market_price: skuItem.form.original_price,
                stock_num: skuItem.form.stock_num,
                skuCoverImage: skuItem.form.image_url != '' ? skuItem.form.image_url : _this.data.this_goods_info.g_img
            });
        }
    },
    videoTimeUpdate:function(e){

    },
    videoPlayAction:function(e){
        let _this = this;
        if(!_this.data.video_is_play){
            var requestData = {};
            requestData.shop_id = _this.data.this_shop_id;
            requestData.goods_id = _this.data.this_goods_id;
            requestData.video_url = _this.data.this_goods_info.g_video_url;
            _requsetCYZ.cyz_requestPost('/ShopFlowApi/addFlowLog', requestData, function (res) {
                wx.hideToast();
                if (res.code == 1) {
                    _this.setData({video_is_play:true})
                } else if (res.code == 2) {
                    app.getUserDataToken(function (token) {
                        _this.videoPlayAction(e);
                    });
                    return false;
                } else {
                    // _functionCYZ.CYZ_alert(res.info);
                    // return false;
                }
            });
        }
    }
})
